package api

import (
	"net/http"
	"io/ioutil"
	"go-web/service"
	"go-web/service/redis"
	"encoding/json"
	"go-web/model"
	"strconv"
	"fmt"
	"go-web/web"
)

func BlogHandler() web.WebHandler {
	return func(writer http.ResponseWriter, request *http.Request) {
		writer.Header().Set("Content-Type", "application/json")
		request.ParseForm()
		method := request.Method
		var cc service.CacheService
		if method == GET {
			idStr := request.Form.Get("id")
			if idStr == "" {
				datas,_ := json.Marshal(PARAM_ERROR)
				writer.Write(datas)
				return
			}
			bl := &model.Blog{Id:123}
			bb,err := bl.Get()
			if err!=nil {
				datas,_ := json.Marshal(ERROR)
				writer.Write(datas)
				return
			}
			fmt.Println(bb.Title)

			cc = &redis.RedisCache{Key:idStr}
			val := cc.GetCache()
			if val == "" {
				datas,_ := json.Marshal(ERROR)
				writer.Write(datas)
				return
			}
			writer.Write([]byte(val))
		} else if method == POST {
			datas,err := ioutil.ReadAll(request.Body)
			if err != nil {
				datas,_ := json.Marshal(PARAM_ERROR)
				writer.Write(datas)
				return
			}
			var blog model.Blog
			err = json.Unmarshal(datas, &blog)
			if err != nil {
				datas,_ := json.Marshal(ERROR)
				writer.Write(datas)
				return
			}
			_,err = blog.Save()
			if err == nil {
				datas,_ := json.Marshal(ERROR)
				writer.Write(datas)
				return
			}

			cc = &redis.RedisCache{Key:strconv.Itoa(blog.Id), Value:datas}
			bo := cc.SetCache()
			if !bo {
				datas,_ := json.Marshal(ERROR)
				writer.Write(datas)
				return
			}
			datas,_ = json.Marshal(SUCCESS)
			writer.Write(datas)
			return

		}
	}
}
